package logic

import (
	"context"
	"fmt"
	"taobao/internal/svc"
	"taobao/models/cache"
	"taobao/models/mysql"
	"taobao/taobao"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsAddLogic {
	return &GoodsAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodsAddLogic) GoodsAdd(in *taobao.AddCartRequest) (*taobao.AddCartResponse, error) {
	// todo: add your logic here and delete this line
	var err error
	var g mysql.Goods
	if err = g.GetGoodsInfoById(in.GoodsId); err != nil {
		logx.Error("商品不存在")
	}
	if g.Stock < int(in.Stock) {
		logx.Error("库存不足了")
	}
	if cache.IsExisit(int(in.UserId), int(in.GoodsId)) {
		fmt.Println("购物车存在此商品")
		cache.UpdateCard(int(in.UserId), int(in.GoodsId), int(in.Stock))
	} else {
		goodsMap := map[string]interface{}{
			"userId":     in.UserId,
			"goodsTitle": in.GoodsTitle,
			"goodsPrice": in.GoodsPrice,
			"stock":      in.Stock,
			"goodsCover": in.GoodsCover,
			"status":     in.Status,
			"checkStaus": 1,
		}
		if err = cache.CartAdd(int(in.UserId), int(in.GoodsId), goodsMap); err != nil {
			logx.Error("添加购物车失败")
			return nil, err
		}
	}
	return &taobao.AddCartResponse{}, nil
}
